package com.da.javatest.thread.juc.base;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author JokerDa.
 * @date 2021/7/8 13:55
 * Description:
 */
public class ReadWriteLockDemo {
    private Map<String, String> cache = new HashMap<>();
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    /**
     * 读数据
     */
    public String get(String key) {
        String value = null;
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读取数据...");
            TimeUnit.MICROSECONDS.sleep(200);
            System.out.println(Thread.currentThread().getName() + "读取数据成功！" + cache.get(key));

            value = cache.get(key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
        return value;
    }

    /**
     * 写数据
     */
    public void put(String key, String value) {
        rwLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "正在写入数据...");
            TimeUnit.MICROSECONDS.sleep(200);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入数据成功！" + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();

        for (int i = 1; i <= 5; i++) {
            int finalI = i;
            new Thread(() -> {
                demo.put(finalI + "", finalI + "");
            }, String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            int finalI = i;
            new Thread(() -> {
                demo.get(finalI + "");
            }, String.valueOf(i)).start();
        }
    }
}
